package com.hongxun.design.utils.mohe;

import android.location.Location;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.hongxun.design.activitys.ReconnaissanceActivity;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.LoadingDialog;
import com.pop.android.common.beans.WzOutLocation;
import com.pop.android.common.util.EvilTransform;
import com.pop.android.location.WzSDKManagerFactory;
import com.pop.android.location.api.outloc.WzChipDiffConfig;
import com.pop.android.location.api.outloc.WzOutLocationListener;
import com.qx.wz.sdk.magicbox.WzMagicBoxFactory;
import com.qx.wz.sdk.magicbox.WzMagicBoxManager;
import com.qx.wz.util.WzUtils;

import static com.hongxun.design.MyApp.activity;

/**
 * Created by zerdoor_pc .
 * author:dc
 * 2016/12/26.
 */

public class MoHeSDKInIt {
    WzChipDiffConfig mWzSdkConfig;
    static MoHeSDKInIt instence;

    public static MoHeSDKInIt getInstence() {
        if (instence == null) {
            instence = new MoHeSDKInIt();
        }
        return instence;
    }

    MoHeSDKInIt() {

    }

    BluetoothUtil2 bluetoothUtil2;

    //应用申请秘钥

    private static final String APP_SECRET = "d52f6b372a1cc26a13749c2155171dcb1db5b495e8f8cfe903b07bc8bf6daec8";//d52f6b372a1cc26a13749c2155171dcb1db5b495e8f8cfe903b07bc8bf6daec8
    //SDK配置管理器
    //location监听器
    private WzOutLocationListener mWzOutLocationListener;
    //sdk是否启动
    private boolean mIsStarted = false;


//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_bluetooth);
//        liner_list = (LinearLayout) findViewById(R.id.liner_list);
//    }


    public void open() {
        isUpdate = true;
       if (bluetoothUtil2==null)bluetoothUtil2 = BluetoothUtil2.getInstence().init(activity, mHandler);
        if (!bluetoothUtil2.getStauts() || mWzSdkConfig == null) {
            bluetoothUtil2.OPenDialog();
            bluetoothUtil2.checkIsOpen();
        }
    }

    public void search() {
        if (bluetoothUtil2 == null)
            bluetoothUtil2 = BluetoothUtil2.getInstence().init(activity, mHandler);
        bluetoothUtil2.OPenDialog();
//        bluetoothUtil2.ensureDiscoverable();
        bluetoothUtil2.getHas();
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case 200:
//                // When the request to enable Bluetooth returns
//                if (resultCode == Activity.RESULT_OK) {
////                setupChat();
//                    Toast.makeText(this, "蓝牙已打开", 0);
//                    if (bluetoothUtil2 == null)
//                        bluetoothUtil2 = new BluetoothUtil2(this, liner_list, mHandler);
//                    bluetoothUtil2.getHas();
//                } else {
//                    Toast.makeText(this, "蓝牙没有打开", 0);
//                    finish();
//                }
//        }
//    }


    /***
     * 启动SDK
     */
    WzMagicBoxManager mWzOutLocationManager;

    boolean isUpdate = true;

    private void startLocation() {
        try {


        //设置WzChipDiffConfig
        if (mWzSdkConfig == null)
            mWzSdkConfig = new WzChipDiffConfig(WzUtils.getAppKey(activity), APP_SECRET, bluetoothUtil2.getAdress(), 1);
        //初始化SDK管理器

        try {
            if (mWzSdkConfig == null) {
                Toast.makeText(activity, "魔盒地址为空", Toast.LENGTH_SHORT).show();
            }
            mWzOutLocationManager = WzMagicBoxFactory.getWzMagicBoxManager(activity, mWzSdkConfig, "D");//magicbox

        } catch (Exception e) {
            Log.i("bluetooth", "" + e.toString());
            Toast.makeText(activity, e.toString(), Toast.LENGTH_SHORT).show();
            return;
        }


        //初始化位置监听
        mWzOutLocationListener = new WzOutLocationListener() {
            @Override
            public void onLocationChanged(WzOutLocation wzOutLocation) {
                if (!isUpdate) return;
                //接收位置数据
                Log.i("bluetooth", "onLocationChanged()" + wzOutLocation.getLongitude());
                Location location = EvilTransform.transform(wzOutLocation);
                Log.i("bluetooth", "getBearing()" + wzOutLocation.getBearing());
                Log.i("bluetooth", "getLatitude()=" + location.getLatitude() + "getLongitude()=" + location.getLongitude());
                String s = "s=" + wzOutLocation.getLongitude() + " getBearing=" + wzOutLocation.getBearing() + "" + "\ngetLatitude()=" + location.getLatitude() + "getLongitude()=" + location.getLongitude();
                // Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
                if (activity instanceof ReconnaissanceActivity)
                    ((ReconnaissanceActivity) activity).setLatlng(wzOutLocation);
            }

            @Override
            public void onStatusChanged(int status) {
                if (!isUpdate) return;
//                Toast.makeText(MoHeSDKInIt.this, "onStatusChanged()=" + status, Toast.LENGTH_SHORT).show();
                Log.i("bluetooth", " onStatusChanged ＝ " + status);
                if (status == 2000 || status == 4000) {
                    bluetoothUtil2.close();
                    ToastShow.showShort(activity, "魔盒链接成功,等待接收数据！");
                    if (activity instanceof ReconnaissanceActivity)
                        ((ReconnaissanceActivity) activity).openDialog();
                } else if (status == 4006) {
//                    ToastShow.showShort(activity,"蓝牙重连中...");
                }

            }

        };
        //获取location
        mWzOutLocationManager.requestLocationUpdates(5000, 1, mWzOutLocationListener, new Handler(), null);
        mIsStarted = true;
        }catch (Exception e){
            ToastShow.showShort(activity,"蓝牙连接异常！");
        }
    }

    public void close() {
        isUpdate = false;
//        try {
//
//            mWzOutLocationManager.removeUpdates(mWzOutLocationListener);
//        }catch (Exception e){}  try {
//
//            bluetoothUtil2.destory();
//        }catch (Exception e){}

    }

    LoadingDialog loadingDialog;
    // The Handler that gets information back from the BluetoothService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothUtil2.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED:
                            System.out.println("bluetooth:已连接");
                            loadingDialog.setText("已连接");
                            break;
                        case BluetoothService.STATE_CONNECTING:
                            loadingDialog = new LoadingDialog(activity);
                            loadingDialog.setText("正在连接...");
                            loadingDialog.setCancelable(false);
                            loadingDialog.show();
                            System.out.println("bluetooth:正在连接...");
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE:
                            System.out.println("bluetooth:无连接");
                            break;
                    }
                    break;
                case BluetoothUtil2.MESSAGE_WRITE:
                    //byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    //String writeMessage = new String(writeBuf);
                    break;
                case BluetoothUtil2.MESSAGE_READ:
                    //byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    //String readMessage = new String(readBuf, 0, msg.arg1);
                    break;
                case BluetoothUtil2.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    if (bluetoothUtil2 != null)bluetoothUtil2.setIsconnect(true);

                    startLocation();
                    String mConnectedDeviceName = msg.getData().getString(BluetoothUtil2.DEVICE_NAME);
                    loadingDialog.setText("连接至"
                            + mConnectedDeviceName);
                    closeDialog();
                    break;
                case BluetoothUtil2.MESSAGE_TOAST:
                    loadingDialog.setText(msg.getData().getString(BluetoothUtil2.TOAST));
                    closeDialog();

                    break;
            }
        }
    };

    private void closeDialog() {
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (loadingDialog != null && loadingDialog.isShowing()) {
                    try {
                        loadingDialog.dismiss();
                        loadingDialog = null;
                    } catch (Exception e) {
                    }
                }
            }
        }, 1000);

    }
}
